package com.jf.docsify.handler;

import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.jf.docsify.common.exception.DocsifyException;
import com.jf.docsify.common.utils.TokenUtil;
import com.jf.docsify.interceptor.AuthInterceptor;
import com.jfinal.handler.Handler;
import com.jfinal.kit.HandlerKit;

/**
 * Description: Md 文件路径 重写
 *
 * @author chenwr
 * @version 1.0
 *
 * <pre>
 * 修改记录:
 * 修改后版本           修改人       修改日期         修改内容
 * 2022/7/25.1       chenwr    2022/7/25           Create
 * </pre>
 * @date 2022/7/25
 */
public class MdUrlRewriteHandler extends Handler {

//    private static final Integer mdSuffixLength = ".md".length();

//    @Override
//    public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
//        if (target != null && target.toLowerCase().endsWith(".md")) {
//            try {
//                target = URLDecoder.decode(target, "utf-8");
//            } catch (Exception e) {
//                throw new RuntimeException("url 解码异常， url path: " + target, e);
//            }
//            String[] targetSplit = target.split("/");
//            String lastUrlPath = targetSplit[targetSplit.length - 1];
//            if (lastUrlPath.startsWith("_")) {
//                target = target.replace(lastUrlPath, lastUrlPath.substring(1));
//            }
//            target = target.substring(0, target.length() - mdSuffixLength);
//            next.handle(target, request, response, isHandled);
//            return;
//        }
//        next.handle(target, request, response, isHandled);
//    }

    @Override
    public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
        try {
            if (target != null && target.toLowerCase().endsWith(".md")) {
                try {
                    target = URLDecoder.decode(target, "utf-8");
                } catch (Exception e) {
                    DocsifyException.throwE("url 解码异常， url path: " + target, e);
                }
                String[] targetSplit = target.replaceFirst("/docs/index/", "").split("/");
                String userId = targetSplit[0];
                String token = TokenUtil.getToken(userId);
                target = "/docs/mdRoute?path=" + URLEncoder.encode(target, "utf-8") + "&" + AuthInterceptor.JWT_KEY + "=" + token;
                HandlerKit.redirect(target, request, response, isHandled);
                return;
            } else if (target != null && target.startsWith("/docs/index") && !"/docs/index".equals(target)) {
                String[] targetSplit = target.replaceFirst("/docs/index/", "").split("/");
                String userId = targetSplit[0];
                target = "/docs/index";
                String token = TokenUtil.getToken(userId);
                request.setAttribute(AuthInterceptor.JWT_KEY, token);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        next.handle(target, request, response, isHandled);
    }
    public String getSessionAttr(HttpServletRequest request, String key) {
        HttpSession session = request.getSession(false);
        return session != null ? (String) session.getAttribute(key) : null;
    }

}